'''
Created on Apr 28, 2011

@author: yc30v1m
'''
import sys
import traceback
from logging import getLogger
log = getLogger(__name__)

class AutoLoad(object):
    '''
    Automatically loads the classes and provides the objects to use
    '''
    def __init__(self):
        pass
    
    @staticmethod
    def ClassAsObject(classFileName, mustLoad = False):
        ''' 
        The FileName and Class name should be same 
        '''
        try:
            obj = AutoLoad.ClassOnly(classFileName)
            return obj()
        except:
            AutoLoad.logExceptionInfo()
            log.debug("Unable to create Instance :" + classFileName)
            log.critical("Exception Creating instance :" + classFileName)
            #if mustLoad == True:
                #raise Exception ,"Class not loaded and Automation Stopped"
    
    @staticmethod
    def ClassOnly(classFileName):
        try:
            components = classFileName.split('.')
            mod = __import__(classFileName, globals(), locals(), [components[len(components)-1]])
            return getattr(mod, components[len(components)-1])
        except:
            AutoLoad.logExceptionInfo()
            log.debug("Unable to Import File at :" + classFileName)
            log.critical("Import Exception :" + classFileName)
            #log.critical(e.__str__)
    
    @staticmethod
    def StaticMethod(classFileName):
        pass
    
    @staticmethod
    def formatExceptionInfo(returnFormattedExec=False,maxTBlevel=5):
        cla, exc, trbk = sys.exc_info()
        excName = cla.__name__
        try:
            excArgs = exc.__dict__["args"]
        except KeyError:
            excArgs = "<no args>"
        excTb = traceback.format_tb(trbk, maxTBlevel)
        if returnFormattedExec == False:
            log.warning("Exception :" + excName)
            log.warning(excArgs)
            log.warning(excTb)
            
        else:
            return (excName, excArgs, excTb)
    
    @staticmethod  
    def logExceptionInfo(maxTBlevel=5):
        AutoLoad.formatExceptionInfo(False, maxTBlevel)
        
